package com.zzyl.nursing.service.impl;

import java.util.*;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.zzyl.common.exception.ServiceException;
import com.zzyl.common.utils.DateUtils;
import com.zzyl.nursing.dto.UserLoginRequestDto;
import com.zzyl.nursing.service.WechatService;
import com.zzyl.nursing.vo.LoginVo;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Service;
import com.zzyl.nursing.mapper.FamilyMemberMapper;
import com.zzyl.nursing.domain.FamilyMember;
import com.zzyl.nursing.service.IFamilyMemberService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

/**
 * 老人家属Service业务层处理
 * 
 * @author alexis
 * @date 2025-09-13
 */
@Service
public class FamilyMemberServiceImpl extends ServiceImpl<FamilyMemberMapper, FamilyMember> implements IFamilyMemberService
{
    @Autowired
    private FamilyMemberMapper familyMemberMapper;

    @Autowired
    private WechatService wechatService;

    @Value("${token.secret}")
    private String secret;

    /**
     * 查询老人家属
     * 
     * @param id 老人家属主键
     * @return 老人家属
     */
    @Override
    public FamilyMember selectFamilyMemberById(Long id)
    {
        return familyMemberMapper.selectById(id);
    }

    /**
     * 查询老人家属列表
     * 
     * @param familyMember 老人家属
     * @return 老人家属
     */
    @Override
    public List<FamilyMember> selectFamilyMemberList(FamilyMember familyMember)
    {
        return familyMemberMapper.selectFamilyMemberList(familyMember);
    }

    /**
     * 新增老人家属
     * 
     * @param familyMember 老人家属
     * @return 结果
     */
    @Override
    public int insertFamilyMember(FamilyMember familyMember)
    {
        return familyMemberMapper.insert(familyMember);
    }

    /**
     * 修改老人家属
     * 
     * @param familyMember 老人家属
     * @return 结果
     */
    @Override
    public int updateFamilyMember(FamilyMember familyMember)
    {
        return familyMemberMapper.updateById(familyMember);
    }

    /**
     * 批量删除老人家属
     * 
     * @param ids 需要删除的老人家属主键
     * @return 结果
     */
    @Override
    public int deleteFamilyMemberByIds(Long[] ids)
    {
        return familyMemberMapper.deleteBatchIds(Arrays.asList(ids));
    }

    /**
     * 删除老人家属信息
     * 
     * @param id 老人家属主键
     * @return 结果
     */
    @Override
    public int deleteFamilyMemberById(Long id)
    {
        return familyMemberMapper.deleteById(id);
    }

    @Override
    public LoginVo login(UserLoginRequestDto userLoginRequestDto) {
        try {
            //1.获取openId
            String openid = wechatService.getOpenid(userLoginRequestDto.getCode());
            //2.根据openId查询用户信息
            FamilyMember familyMember = familyMemberMapper.selectOne(new LambdaQueryWrapper<FamilyMember>()
                    .eq(FamilyMember::getOpenId, openid));
            //判断用户信息是否为空，为空则需要创建新的 用户并赋值openid
            if (familyMember == null) {
                familyMember = new FamilyMember();
                familyMember.setOpenId(openid);
            }
            //3.获取手机号
            String phone = wechatService.getPhone(userLoginRequestDto.getPhoneCode());
            familyMember.setPhone(phone);
            //4.新增或更新用户信息
            if (familyMember.getId() == null){
                familyMember.setName(generateRandomName()); // 修复：使用正确的方法名
                familyMemberMapper.insert(familyMember);
            }else {
                familyMemberMapper.updateById(familyMember);
            }
            //5.生成jwt令牌并返回
            Map<String, Object> claims = new HashMap<>();
            claims.put("userId", familyMember.getId());
            claims.put("nickName", familyMember.getName()); // 修复：使用正确的键名
            String token = Jwts.builder()
                    .setClaims(claims)
                    .signWith(SignatureAlgorithm.HS512, secret)
                    .setExpiration(new Date(System.currentTimeMillis() + 9000 * 1000)) // 设置过期时间
                    .compact();
            return LoginVo.builder()
                    .token(token)
                    .nickName(familyMember.getName()) // 修复：使用正确的方法名和变量名
                    .build();
        } catch (Exception e) {
            log.error("用户登录失败", e);
            throw new ServiceException("登录失败: " + e.getMessage());
        }
    }



    /**
     * 生成真实感的随机名称
     * @return 随机生成的名称
     */
    public String generateRandomName() {
        // 常见姓氏
        String[] surnames = {
                "王", "李", "张", "刘", "陈", "杨", "赵", "黄", "周", "吴",
                "徐", "孙", "胡", "朱", "高", "林", "何", "郭", "马", "罗",
                "梁", "宋", "郑", "谢", "韩", "唐", "冯", "于", "董", "萧"
        };

        // 常见名字(适合老年人)
        String[] givenNames = {
                "建国", "建军", "国强", "国华", "国平", "国良", "国栋", "国荣", "国辉", "国强",
                "秀英", "秀兰", "秀芳", "秀珍", "秀琴", "秀华", "秀梅", "秀红", "秀云", "秀莲",
                "志强", "志华", "志明", "志刚", "志勇", "志军", "志伟", "志峰", "志超", "志斌",
                "爱华", "爱民", "爱军", "爱玲", "爱芳", "爱珍", "爱萍", "爱英", "爱霞", "爱美",
                "建华", "建民", "建平", "建明", "建强", "建峰", "建伟", "建刚", "建勇", "建辉",
                "淑英", "淑华", "淑兰", "淑珍", "淑芳", "淑琴", "淑梅", "淑萍", "淑云", "淑红"
        };

        // 现代常用名字
        String[] modernNames = {
                "伟", "芳", "娜", "敏", "静", "丽", "强", "磊", "军", "洋",
                "勇", "艳", "杰", "娟", "涛", "明", "超", "秀英", "霞", "平",
                "刚", "桂英", "丽华", "丹", "萍", "华", "红", "玉兰", "桂兰", "玲"
        };

        Random random = new Random();

        // 70%概率使用传统姓名组合，30%概率使用现代姓名
        if (random.nextInt(100) < 70) {
            // 传统姓名：姓氏+名字
            String surname = surnames[random.nextInt(surnames.length)];
            String givenName = givenNames[random.nextInt(givenNames.length)];
            return surname + givenName;
        } else {
            // 现代姓名：姓氏+1-2个字的名字
            String surname = surnames[random.nextInt(surnames.length)];
            String givenName;
            if (random.nextBoolean()) {
                // 单字名
                givenName = modernNames[random.nextInt(modernNames.length)].substring(0, 1);
            } else {
                // 双字名
                givenName = modernNames[random.nextInt(modernNames.length)];
            }
            return surname + givenName;
        }
    }

}
